package real.realschool;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import com.acecounter.logging.android.AMZLogEventAPI;
import com.acecounter.logging.android.AutoLoggingActivity;

import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.GestureDetector.OnGestureListener;
import android.view.View.OnClickListener;

public class Real_WEB extends Activity {

	public static StaticAct Activity = StaticAct.getInstance();
	
	WebView wv;
	TextView home, write;
	Intent intent;
	Button cj_one, user, packages, sale, button, pic_upload;
	Intent intend, paks, sales;
	EditText nick, commen;
	String ni, com, urlTime;

	private static final int REQ_CODE_PICK_IMAGE = 0;
	private static final int PICK_FROM_ALBUM = 1;
	private static final int CROP_FROM_CAMERA = 2;
	private static Bitmap LAST_BMP, FIRST_BMP, resizedx;
	/** Called when the activity is first created. */
	private static final int CAMERA_PIC_REQUEST = 1337;
	private static final String TEMP_PHOTO_FILE = "temporary_holder.jpg";
	Location lastLocation = null;
	private LocationManager locationMgr;
	double geo_w = 0, geo_g = 0;
	final static int GALLERY_RESULT = 0;
	private Uri mImageCaptureUri, imgUri, testUri;
	private Bitmap bmp;
	private ImageView imv;
	private String phoneNumber;
	private Defence_Injection df = new Defence_Injection();

	private ArrayList<String> nickname = new ArrayList();
	private ArrayList<String> phoneNum = new ArrayList();

	Context context = null;
	private String url;
	int check_for = 0;
	int pic_check = 0;

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();

		AMZLogEventAPI amzLog = AMZLogEventAPI.getInstance(this);
		amzLog.onViewPages(this);
	}

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.talk_web);

		context = this;

		Activity.at.add(this);

		home = (TextView) findViewById(R.id.textView1);
		home.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				finish();
			}
		});

		TelephonyManager manager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
		phoneNumber = manager.getLine1Number();

		url = "http://"+ Activity.ip+ "/StudyProject/Realschool/login/real_namecheck_view.jsp?phoneNumber="+ phoneNumber;

		// XML Parsing

		try {

			URL text = new URL(url);

			XmlPullParserFactory parserCreator = XmlPullParserFactory.newInstance();

			XmlPullParser parser = parserCreator.newPullParser();

			parser.setInput(text.openStream(), null);

			int parserEvent = parser.getEventType();
			String tag;

			boolean inTitle = false, inTitle2 = false;
			while (parserEvent != XmlPullParser.END_DOCUMENT) {

				switch (parserEvent) {

				case XmlPullParser.TEXT:

					tag = parser.getName();
					if (inTitle) {
						String max = parser.getText();
						nickname.add(max); // 파싱한 별명 객체에 추가
					} else if (inTitle2) {
						String max = parser.getText();
						phoneNum.add(max);
					}

					break;

				case XmlPullParser.END_TAG:
					tag = parser.getName();
					if (tag.compareTo("nick") == 0) {
						inTitle = false;
					} else if (tag.compareTo("phone") == 0) {
						inTitle2 = false;
					}

					break;

				case XmlPullParser.START_TAG:
					tag = parser.getName();

					if (tag.compareTo("nick") == 0) {
						inTitle = true;
					} else if (tag.compareTo("phone") == 0) {
						inTitle2 = true;
					}

					break;
				}
				parserEvent = parser.next();
			}
		} catch (Exception e) {
			Log.e("dd", "Error in network call", e);
		}

		for (int loop = 0; loop < nickname.size(); loop++) {

			if (phoneNum.get(loop).equals(phoneNumber)) {
				Activity.editnick = nickname.get(loop);
				loop = phoneNum.size();
			}

		}

		if (Activity.editnick == null) {
			Activity.editnick = "닉네임";
		}

		write = (TextView) findViewById(R.id.textView4);
		write.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub

				LinearLayout li = (LinearLayout) View.inflate(Real_WEB.this,
						R.layout.real_dialog, null);

				nick = (EditText) li.findViewById(R.id.nick_var);
				commen = (EditText) li.findViewById(R.id.comment_var);
				pic_upload = (Button) li.findViewById(R.id.pic_upload);

				if (phoneNumber.equals("01077376349")) {
					nick.setText("정성준(개발자)");
				} else if (phoneNumber.equals(" 821095354268")) {
					nick.setText("에너지넘치는창민이");
				} else {
					nick.setText(Activity.editnick);
				}

				pic_upload.setOnClickListener(new OnClickListener() {

					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						Intent intent = new Intent();
						intent.setAction(Intent.ACTION_PICK);

						intent.setType(android.provider.MediaStore.Images.Media.CONTENT_TYPE);
						intent.setData(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

						intent.setType("image/*");

						startActivityForResult(intent, 5);
						Activity.pic_check = 1;
					}
				});

				final AlertDialog.Builder build = new AlertDialog.Builder(
						Real_WEB.this);
				build.setView(li)
						.setPositiveButton("확인",
								new DialogInterface.OnClickListener() {

									public void onClick(DialogInterface dialog,
											int which) {

										if (df.Defence(nick.getText().toString())&& df.Defence(commen.getText().toString())) { // SQL injection 검사

											ni = " " + nick.getText().toString();
											com = " "+ commen.getText().toString();

											WebView wv = (WebView) findViewById(R.id.webView);
											wv.getSettings().setJavaScriptEnabled(true);

											Date today = new Date();
											SimpleDateFormat format = new SimpleDateFormat(
													"yyyy-MM-dd/hh:mm:ss");
											SimpleDateFormat format1 = new SimpleDateFormat(
													"yyyyMMddhhmmss");

											String strDate = format
													.format(today);
											String pic = format1.format(today);
											Activity.strDate = pic;

											TelephonyManager manager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);

											String phoneNumber = manager
													.getLine1Number();

											Toast.makeText(Real_WEB.this,
													"등록 되었습니다.",
													Toast.LENGTH_SHORT).show();

											wv.loadUrl("http://"
													+ Activity.ip
													+ "/StudyProject/Realschool/real_input.jsp?&date="
													+ strDate + "&nick=" + ni
													+ "&comment=" + com
													+ "&phoneNum="
													+ phoneNumber + "&pic="
													+ pic + "&pic_check="
													+ pic_check);
											onClickUpload();
											pic_check = 0;

											try {
												Thread.sleep(500);
											} catch (InterruptedException e) {
												// TODO Auto-generated catch
												// block
												e.printStackTrace();
											}

											wv = (WebView) findViewById(R.id.webView1);
											wv.getSettings()
													.setJavaScriptEnabled(true);
											wv.loadUrl("http://"
													+ Activity.ip
													+ "/StudyProject/Realschool/real_view.jsp");

										} else {
											Toast.makeText(Real_WEB.this,
													"특수문자는 사용하실 수 없습니다.",
													Toast.LENGTH_SHORT).show();
											df.check = true;
										}
									}
								})
						.setTitle("게시물 등록")
						.setMessage("게시물을 등록하시고 싶으면 \n 닉네임과 코멘트를 입력하시면 됩니다^^")
						.setNegativeButton("취소",
								new DialogInterface.OnClickListener() {

									public void onClick(DialogInterface dialog,
											int which) {
										// TODO Auto-generated method stub

									}
								}).show();

			}

		});

		wv = (WebView) findViewById(R.id.webView1);
		wv.setWebViewClient(new HelloWebViewClient());
		wv.getSettings().setJavaScriptEnabled(true);
		wv.setHorizontalScrollBarEnabled(false);
		wv.setVerticalScrollBarEnabled(true);

		wv.loadUrl("http://" + Activity.ip
				+ "/StudyProject/Realschool/real_view.jsp");
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu2, menu);

		menu.findItem(R.id.menu01).setTitle("프로필사진");
		menu.findItem(R.id.menu01).setIcon(real.realschool.R.drawable.man);

		return true;
	}

	public boolean onOptionsItemSelected(Menu menu) {
		super.onPrepareOptionsMenu(menu);
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {

		case R.id.menu01: {
			Intent intent = new Intent();

			intent.setAction(Intent.ACTION_PICK);

			intent.setType(android.provider.MediaStore.Images.Media.CONTENT_TYPE);
			intent.setData(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

			intent.setType("image/*");

			startActivityForResult(intent, 4);
			Activity.pic_check = 0;
		}
			return true;

		}
		return super.onOptionsItemSelected(item);
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK)) {

			finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	class HelloWebViewClient extends WebViewClient {
		ProgressDialog mProgress;

		public boolean shouldOverrideUrlLoading(WebView view, String url) {

			Intent men1 = new Intent(Real_WEB.this, Real_WEB_Detail.class);
			startActivity(men1);

			Activity.detail_url = url; // 클릭했을 때 이동하는 URL

			return true;
		}

		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			if (mProgress == null) {
				try {
					mProgress = new ProgressDialog(Real_WEB.this);
					mProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
					mProgress.setTitle("로딩 중 ...");
					mProgress.setMessage("경성대 학생들의 후기를 불러오고 있습니다.^^");
					mProgress.setCancelable(false);

					mProgress.show();
				} catch (IllegalArgumentException e) {

				}
			}
		}

		public void onReceivedError(WebView view, int errorCode,
				String description, String failingUrl) {

		}

		public void onPageFinished(WebView view, String url) {
			if (mProgress.isShowing()) {

				try {
					mProgress.dismiss();
				} catch (IllegalArgumentException e) {

				}
			}
		}
	}

	protected void onActivityResult(int requestCode, int resultCode,
			Intent imageReturnedIntent) {
		super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

		switch (requestCode) {

		case 4: { // 프로필사진 Resize 할 크기 결정. (Crop)

			try {
				mImageCaptureUri = imageReturnedIntent.getData();

				Intent intent = new Intent("com.android.camera.action.CROP");

				intent.setDataAndType(mImageCaptureUri, "image/*");
				intent.putExtra("crop", "true");
				intent.putExtra("outputX", 500);
				intent.putExtra("outputY", 500);
				intent.putExtra("aspectX", 1);
				intent.putExtra("aspectY", 1);

				intent.putExtra(MediaStore.EXTRA_OUTPUT, getTempUri());
				intent.putExtra("outputFormat",
						Bitmap.CompressFormat.JPEG.toString());

				startActivityForResult(intent, 44);
			} catch (NullPointerException e) {
				startActivity(new Intent(this, Real_WEB.class));
			}
			break;
		}

		case 44: // 프로필사진 이미지를 넘겨 받는다.
			if (resultCode == RESULT_OK) {
				if (imageReturnedIntent != null) {

					File tempFile = getTempFile();

					String filePath = Environment.getExternalStorageDirectory() // 파일이
																				// 저장되는곳
							+ "/temporary_holder.jpg";

					FIRST_BMP = BitmapFactory.decodeFile(filePath); // 디코딩
					LAST_BMP = BitmapFactory.decodeFile(filePath);
					Date today = new Date();
					SimpleDateFormat format1 = new SimpleDateFormat(
							"yyyyMMddhhmmss");
					String pic = format1.format(today);
					Activity.strDate = pic; // 미리 값을 지정해야한다.

					onClickUpload();

				}
			}
			break;

		case 5: { // Upload 사진 Resize 할 크기 결정. (Crop)

			try {
				mImageCaptureUri = imageReturnedIntent.getData();

				Intent intent = new Intent("com.android.camera.action.CROP");

				intent.setDataAndType(mImageCaptureUri, "image/*");
				intent.putExtra("crop", "true");
				intent.putExtra("outputX", 500);
				intent.putExtra("outputY", 500);
				intent.putExtra("aspectX", 1);
				intent.putExtra("aspectY", 1);

				intent.putExtra(MediaStore.EXTRA_OUTPUT, getTempUri());
				intent.putExtra("outputFormat",
						Bitmap.CompressFormat.JPEG.toString());

				startActivityForResult(intent, REQ_CODE_PICK_IMAGE);

			} catch (NullPointerException e) {
				startActivity(new Intent(this, Real_WEB.class));
			}
			break;
		}

		case REQ_CODE_PICK_IMAGE: // crop 후의 이미지를 넘겨 받는다.
			if (resultCode == RESULT_OK) {
				if (imageReturnedIntent != null) {

					File tempFile = getTempFile();

					String filePath = Environment.getExternalStorageDirectory() // 파일이
																				// 저장되는곳
							+ "/temporary_holder.jpg";

					FIRST_BMP = BitmapFactory.decodeFile(filePath); // 디코딩
					LAST_BMP = BitmapFactory.decodeFile(filePath);
					pic_upload.setText("첨부 완료");

					pic_check = 1;
				}
			}
			break;

		}

		try {

			bmp.recycle();

			imgUri = imageReturnedIntent.getData(); // 사진의 URI 가져오기

			bmp = Images.Media.getBitmap(getContentResolver(), imgUri);

			imv.setImageBitmap(bmp);

			// imv.setImageURI(data.getDate()); // 사진의 URI 가져오기
			// imv.setImageURI(imageReturnedIntent.getData());

		} catch (Exception e) {

			e.printStackTrace();

		}
	}

	private Uri getTempUri() {
		return Uri.fromFile(getTempFile());
	}

	private boolean isSDCARDMounted() {
		String status = Environment.getExternalStorageState();
		if (status.equals(Environment.MEDIA_MOUNTED))
			return true;
		return false;
	}

	private File getTempFile() {
		if (isSDCARDMounted()) {

			File f = new File(Environment.getExternalStorageDirectory(),
					TEMP_PHOTO_FILE);
			try {
				f.createNewFile();
			} catch (IOException e) {

			}
			return f;
		} else {
			return null;
		}
	}

	private ProgressDialog loagindDialog;

	public void onClickUpload() {
		/* ProgressDialog */

		// 로딩 바

		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
		
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inSampleSize = 4;

		try {
			Bitmap resized = Bitmap.createScaledBitmap(LAST_BMP, 500, 500,
					false);

			FileOutputStream fos;

			try {

				SimpleDateFormat form = new SimpleDateFormat("yyyy-MM-dd-hh",
						Locale.KOREA);
				Date dTime = new Date();
				urlTime = form.format(dTime);

				if (Activity.pic_check == 0) {
					fos = openFileOutput(phoneNumber + "1.png", 0); // 파일열기
				} else {
					fos = openFileOutput(Activity.strDate + ".png", 0);
				}
				resized.compress(CompressFormat.JPEG, 100, fos); // jpg로 변환

				fos.flush();
				fos.close();
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}

			
					File file;

					if (Activity.pic_check == 0) {
						file = new File("data/data/real.realschool/files/"
								+ phoneNumber + "1.png"); // 선택한 사진

					} else {
						file = new File("data/data/real.realschool/files/"
								+ Activity.strDate + ".png"); // 선택한 사진
					}
					Activity.filename = Activity.strDate + ".png";

					try {
						String postURL;

						HttpClient client = new DefaultHttpClient();

						if (Activity.pic_check == 0) { // 프로필사진 -> DB등록
							postURL = "http://" + Activity.ip
									+ "/StudyProject/profile/upload.jsp";
						} else {
							postURL = "http://" + Activity.ip
									+ "/StudyProject/profile/upload_pic.jsp";
						}
						HttpPost post = new HttpPost(postURL);

						post.setHeader("Connection", "Keep-Alive");
						post.setHeader("Accept-Charset", "euc-kr");
						post.setHeader("ENCTYPE", "multipart/form-data"); // multipart
																			// 형태로
																			// 만들어준다

						FileBody bin = new FileBody(file);
						MultipartEntity reqEntity = new MultipartEntity(
								HttpMultipartMode.BROWSER_COMPATIBLE);

						reqEntity.addPart("fileName", bin);

						StringBody phones = new StringBody(phoneNumber, null);
						reqEntity.addPart("phone", phones);

						StringBody date = new StringBody(Activity.strDate, null);
						reqEntity.addPart("date", date);

						post.setEntity(reqEntity);

						HttpResponse response = client.execute(post);
						HttpEntity resEntity = response.getEntity();

						if (resEntity != null) {
							Log.i("RESPONSE", EntityUtils.toString(resEntity));
						}
					} catch (Exception e) {
						e.printStackTrace();
						Log.e("1", "예외");
					}
				
			try {
				File delfile = new File("data/data/real.realschool/files/");
				File[] flist = delfile.listFiles();

				for (int i = 0; i < flist.length; i++) {
					String fname = flist[i].getName();
					if (fname.equals(phoneNumber + "1.png")) {
						flist[i].delete();
					} else if (fname.equals(Activity.strDate + ".png")) {
						flist[i].delete();
					}
				}

			} catch (Exception e) {
				e.printStackTrace();
			}

		} catch (NullPointerException e) {
			e.printStackTrace();
			// Toast.makeText(KSU_WEB.this, "사진을 선택하세요.",
			// Toast.LENGTH_LONG).show();
		}

			}
		}).start();

		
		Toast.makeText(Real_WEB.this, "사진이 등록되었습니다.", Toast.LENGTH_LONG)
		.show();
	}

	private Handler handler2 = new Handler() {
		public void handleMessage(Message msg) {
			loagindDialog.dismiss();
		}
	};

	public Drawable loadDrawable(String urlStr) {
		Drawable drawable = null;

		try {
			URL url = new URL(urlStr);
			InputStream is = url.openStream();
			drawable = Drawable.createFromStream(is, "none");
		} catch (Exception e) {
			// Log.e("LOG_TAG", "error, in loadDrawable \n" + e.toString());
		}

		return drawable;
	}

	public void onBackPressed() {
		if (wv.canGoBack()) {
			wv.goBack();
			finish();
		}
	}

}